import 'package:get/get.dart';
import 'package:oramemo/entity/create_order_entity.dart';
import 'package:oramemo/entity/membr_level_entity.dart';
import '../repositories/transaction_repository.dart';
import '../models/transaction.dart';

class TransactionController extends GetxController {
  final TransactionRepository _repository = TransactionRepository();
  final _isLoading = false.obs;
  final RxList<MembrLevelData> _memberLevels = <MembrLevelData>[].obs;
  final RxList<Transaction> _transactions = <Transaction>[].obs;

  bool get isLoading => _isLoading.value;
  List<MembrLevelData> get memberLevels => _memberLevels;
  List<Transaction> get transactions => _transactions;

  @override
  void onInit() {
    super.onInit();
  }

  Future<void> fetchMemberLevels() async {
    try {
      _isLoading.value = true;
      final response = await _repository.getMemberLevels();
      if (response.isSuccess && response.data?.data != null) {
        _memberLevels.value = response.data!.data!;
      } else {
        Get.snackbar('Error', response.msg);
      }
    } catch (e) {
      Get.snackbar('Error', e.toString());
    } finally {
      _isLoading.value = false;
    }
  }

  Future<void> fetchTransactions({
    required int page,
    required int size,
    String? type,
    String? status,
  }) async {
    try {
      _isLoading.value = true;
      final response = await _repository.getTransactions(
        page: page,
        size: size,
        type: type,
        status: status,
      );
      if (response.isSuccess && response.data != null) {
        _transactions.value = response.data!;
      } else {
        Get.snackbar('Error', response.msg);
      }
    } catch (e) {
      Get.snackbar('Error', e.toString());
    } finally {
      _isLoading.value = false;
    }
  }

  Future<CreateOrderData?> createOrder({
    required String memberLevelId,
    String? couponCode,
  }) async {
    try {
      _isLoading.value = true;
      final response = await _repository.createOrder(
        memberLevelId: memberLevelId,
        couponCode: couponCode,
      );
      if (response.isSuccess) {
        Get.snackbar('Success', 'Order created successfully');
        return response.data?.data;
      } else {
        Get.snackbar('Error', response.msg);
      }
    } catch (e) {
      Get.snackbar('Error', e.toString());
    } finally {
      _isLoading.value = false;
    }
    return null;
  }
}